﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.DomainServices.Server.ApplicationServices;
using System.ServiceModel.DomainServices.Hosting;
using NetBay.Core.BusinessEntities;

namespace Rio.Applications.Web.Services.Authentication
{
    [EnableClientAccess]
    public class AuthenticationService : IAuthentication<AuthenticationUser>
    {
        private static AuthenticationUser _authenticationUser;

        public AuthenticationUser GetUser()
        {
            return _authenticationUser;
        }

        public AuthenticationUser Login(string userName, string password, bool isPersistent, string customData)
        {
            if (_authenticationUser == null)
            {
                using (BusinessEntitiesDomainService service = new BusinessEntitiesDomainService())
                {
                    List<User> users = new List<User>(service.GetAccess(userName, password, Int32.MaxValue));
                    User user = users.FirstOrDefault();

                    _authenticationUser = new AuthenticationUser(user);
                }
            }

            return _authenticationUser;
        }

        public AuthenticationUser Logout()
        {
            using (BusinessEntitiesDomainService service = new BusinessEntitiesDomainService())
            {
                service.Disconnect();
            }

            _authenticationUser = null;

            return _authenticationUser;
        }

        public void UpdateUser(AuthenticationUser user)
        {
            throw new NotImplementedException();
        }
    }
}